package com.idas.comp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.idas.comp.enums.Status;

public class UserAccess {
	
	private static Logger logger = Logger.getLogger(UserAccess.class);
	
	private User user;
	private long userId;
	private UserPermissions permissions;
	
	public UserAccess(){}

	protected UserAccess(ResultSet rs)throws SQLException{
		user = new User(rs);
		userId = rs.getLong("user_id");
		permissions = new UserPermissions(rs.getInt("permission_value"));
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public long getUserId() {
		return userId;
	}

	public void setUserId(long userId) {
		this.userId = userId;
	}

	public UserPermissions getPermissions() {
		return permissions;
	}

	public void setPermissions(UserPermissions permissions) {
		this.permissions = permissions;
	}
	
	public static UserAccess autenticateUser(Connection conn, String email,
			String password) throws SQLException {
		UserAccess uac = null;
		
		String sql = "SELECT su.*, u.* ut.permisson_value FROM system_uuid su, user u, usertype ut WHERE " +
				"u.uuid = su.system_uuid AND u.usertype_id = ut.usertype_id AND u.email = ? AND u.password = PASSWORD(?) AND u.active > 1";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, email);
		ps.setString(2, password);
		
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			uac = new UserAccess(rs);
		}
		
		if (null==uac){
			logger.error("Non validated user");
		}
		
		return uac;
	}

}
